package com.so206.aop;

import com.so206.plugins.MyCacheManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Objects;

/**
 * 防止重复提交
 */
@Aspect
@Component
@Order(-1)
public class NoRepeatSubmitAop {

    private static final Logger logger = LoggerFactory.getLogger(NoRepeatSubmitAop.class);

    public NoRepeatSubmitAop() {
        logger.info("NoRepeatSubmitAop Init...");
    }

    @Autowired
    private MyCacheManager template;

    @Around("@annotation(com.so206.aop.NoRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).getSessionId();
            HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
            String key = sessionId.trim() + ":" + request.getRequestURI().trim();
            synchronized (key.intern()) {
                if (template.get(key) == null) {// 如果缓存中有这个url视为重复提交
                    Object proceed = pjp.proceed();
                    template.set(key, "NoRepeatSubmit", 2000);
                    return proceed;
                } else {
                    throw new Exception("数据重复提交,请稍后重试!");
                }
            }
        } catch (Throwable e) {
            logger.error(e.getMessage());
            HashMap<Object, Object> map = new HashMap<>();
            map.put("code", -1);
            map.put("msg", e.getMessage());
            return map;
        }

    }


}
